<?php
/**
 *
 * 版权所有：安德玛(underArmour)
 * 作    者：1554324405@qq.com
 * 日    期：2020-05-20
 * 版    本：1.0.0
 * 功能说明：支付回调控制器。
 *
 **/
namespace Api\Controller;

class PaynotifyController extends BaseController
{
    /**
     * 购买用户等级支付回调
     */
    public function userLevel()
    {
        // $paysapi_id = $_POST["paysapi_id"];
        // $orderid = $_POST["orderid"];
        // $price = $_POST["price"];
        // $realprice = $_POST["realprice"];
        // $orderuid = $_POST["orderuid"];
        // $key = $_POST["key"];
        
        // //校验传入的参数是否格式正确，略
        
        // $token = "da4d1ab652ff92567cff29e86eaff931";
        
        // $temps = md5($orderid . $orderuid . $paysapi_id . $price . $realprice . $token);
        // if ($temps != $key){
        //     $this->res['code'] = -1;
        //     $this->res['msg'] = 'key值不匹配';
        //     $this->response($this->res,'json');
        // }else{
        //     //校验key成功，是自己人。执行自己的业务逻辑：加余额，订单付款成功，装备购买成功等等。
        //     $order_info = M('user_level_buy')->where(array('order_no'=>$orderid))->find();
        //     if(empty($order_info)){
        //         $this->res['code'] = -1;
        //         $this->res['msg'] = '记录不存在';
        //         $this->response($this->res,'json');
        //     }
        //     // 更改支付状态
        //     M('user_level_buy')->data(array('status'=>2,'finish_t'=>time()))->where('id='.$order_info['id'])->save();
        //     //加入消息通知
        //     $user_level_buy = M('user_level_buy')->where('id='.$order_info['id'])->field('uid,level_id')->find();
        //     $level = M('user_level')->where('id='.$user_level_buy['level_id'])->field('title')->find();
        //     M('user_message')->data(array('uid'=>$user_level_buy['uid'],'content'=>'会员等级成功升级为'.$level['title'],'t'=>time(),'type'=>2))->add();
        //     //推荐奖励
        //     $this->getReward($order_info['id']);
        //     //更新用户等级相关信息
        //     $this->updateUserLevelInfo($order_info['id']);
        //     $this->res['code'] = 1;
        //     $this->res['msg'] = 'success';
        //     $this->response($this->res,'json');
        // }
		 // vendor('SDK.lib.epay_notify#class');
		// //计算得出通知验证结果
		// $alipayNotify = new \AlipayNotify($alipay_config);
		// $verify_result = $alipayNotify->verifyNotify();
		
		// if($verify_result) {//验证成功
			/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代
		
			$out_trade_no = $_GET['out_trade_no'];
		
			//彩虹易支付交易号
		
			$trade_no = $_GET['trade_no'];
		
			//交易状态
			$trade_status = $_GET['trade_status'];
		
			//支付方式
			$type = $_GET['type'];
		
		
			if ($trade_status == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
					//如果有做过处理，不执行商户的业务程序
					$order_info = M('user_level_buy')->where(array('order_no'=>$out_trade_no))->find();
				       M('user_level_buy')->data(array('status'=>2,'finish_t'=>time()))->where('id='.$order_info['id'])->save();
				       //加入消息通知
				       $user_level_buy = M('user_level_buy')->where('id='.$order_info['id'])->field('uid,level_id')->find();
				       $level = M('user_level')->where('id='.$user_level_buy['level_id'])->field('title')->find();
				       M('user_message')->data(array('uid'=>$user_level_buy['uid'],'content'=>'会员等级成功升级为'.$level['title'],'t'=>time(),'type'=>2))->add();
				       //推荐奖励
				       $this->getReward($order_info['id']);
				       //更新用户等级相关信息
				       $this->updateUserLevelInfo($order_info['id']);
				       $this->res['code'] = 1;
				       $this->res['msg'] = 'success';
				       $this->response($this->res,'json');
		
		    }
        
    }
    
    /**
     * 购买任务支付回调
     */
    public function publishTask()
    {
        $paysapi_id = $_POST["paysapi_id"];
        $orderid = $_POST["orderid"];
        $price = $_POST["price"];
        $realprice = $_POST["realprice"];
        $orderuid = $_POST["orderuid"];
        $key = $_POST["key"];
        
        //校验传入的参数是否格式正确，略
        
        $token = "da4d1ab652ff92567cff29e86eaff931";
        
        $temps = md5($orderid . $orderuid . $paysapi_id . $price . $realprice . $token);
        if ($temps != $key){
            $this->res['code'] = -1;
            $this->res['msg'] = 'key值不匹配';
            $this->response($this->res,'json');
        }else{
            //校验key成功，是自己人。执行自己的业务逻辑：加余额，订单付款成功，装备购买成功等等。
            $order_info = M('task')->where(array('id'=>$orderid))->find();
            if(empty($order_info)){
                $this->res['code'] = -1;
                $this->res['msg'] = '记录不存在';
                $this->response($this->res,'json');
            }
            // 更改支付状态
            M('task')->data(array('pay_status'=>1,'update_t'=>time()))->where('id='.$orderid)->save();
            //加入消息通知
            $task = M('task')->where('id='.$orderid)->field('title,uid')->find();
            M('user_message')->data(array('uid'=>$task['uid'],'content'=>'成功发布任务'.$task['title'],'t'=>time(),'type'=>2))->add();
            $this->res['code'] = 1;
            $this->res['msg'] = 'success';
            $this->response($this->res,'json');
        }
    }
    
    
    /**
     * 根据订单id获取推荐奖励
     * @param string $order_no
     */
    private function getReward($order_id=0)
    {
        $order_info = M('user_level_buy')->where('id='.$order_id)->find();
        $money = floatval($order_info['money']);
        $uid = $order_info['uid'];
        // 一级推介用户奖励逻辑
        $first_pid_info = M('user')->where('id='.$uid)->field('pid')->find();
        if($first_pid_info['pid']){
            $first_user_info = M('user')->where('id='.$first_pid_info['pid'])->find();
            if($first_user_info['status'] == 1 && strtotime($first_user_info['expri_day']) > time()){
                // 计算一级推介用户的用户等级及一级推荐奖励
                $first_user_level_info = M('user_level')->where('id='.$first_user_info['level_id'])->field('jiangli_1')->find();
                $percent = intval($first_user_level_info['jiangli_1']);
                if($percent > 0){
                    // 插入奖励记录
                    $jl_price = round($money * $percent / 100,2);
                    //更新余额
                    M('user')->where('id='.$first_user_info['id'])->setInc('money',$jl_price);
                    //插入收益记录
                    $income_data = array(
                        'money'=>$jl_price,
                        'type'=>4,
                        't'=>time(),
                        'remark'=>'一级用户推荐奖励'.$jl_price.'元',
                        'uid'=>$first_user_info['id']
                    );
                    M('user_income')->data($income_data)->add();
                    // 加入会员动态（一级用户推荐奖励）
                    M('user_dynamic')->data(array('mobile'=>$first_user_info['username'],'content'=>'成功获得一级用户推荐奖励','t'=>time()))->add();
                    // 加入消息通知
                    M('user_message')->data(array('uid'=>$first_user_info['id'],'content'=>'一级用户推荐奖励'.$jl_price.'元','t'=>time(),'type'=>2))->add();
                }
            }
            // 二级推介用户奖励逻辑
            if($first_user_info['pid']){
                $second_user_info = M('user')->where('id='.$first_user_info['pid'])->find();
                if($second_user_info['status'] == 1 && strtotime($second_user_info['expri_day']) > time()){
                    // 计算二级推介用户的用户等级及二级推荐奖励
                    $second_user_level_info = M('user_level')->where('id='.$second_user_info['level_id'])->field('jiangli_2')->find();
                    $percent = intval($second_user_level_info['jiangli_2']);
                    if($percent > 0){
                        // 插入奖励记录
                        $jl_price = round($money * $percent / 100,2);
                        //更新余额
                        M('user')->where('id='.$second_user_info['id'])->setInc('money',$jl_price);
                        //插入收益记录
                        $income_data = array(
                            'money'=>$jl_price,
                            'type'=>5,
                            't'=>time(),
                            'remark'=>'二级用户推荐奖励'.$jl_price.'元',
                            'uid'=>$second_user_info['id']
                        );
                        M('user_income')->data($income_data)->add();
                        // 加入会员动态（二级用户推荐奖励）
                        M('user_dynamic')->data(array('mobile'=>$second_user_info['username'],'content'=>'成功获得二级用户推荐奖励','t'=>time()))->add();
                        // 加入消息通知
                        M('user_message')->data(array('uid'=>$second_user_info['id'],'content'=>'二级用户推荐奖励'.$jl_price.'元','t'=>time(),'type'=>2))->add();
                    }
                }
            }
        }
    }
    
    /**
     * 更新用户等级相关信息
     * @param number $order_id
     */
    private function updateUserLevelInfo($order_id=0)
    {
        $order_info = M('user_level_buy')->where('id='.$order_id)->find();
        // 计算该等级有效天数
        $level_info = M('user_level')->where('id='.$order_info['level_id'])->field('expri_day,title')->find();
        $days = intval($level_info['expri_day']);
		/*
		1:普通会员
		3:黄金会员
		4:铂金会员
		5:钻石会员
		6:网红
		*/
		if($order_info['level_id'] == 3){
			$show_newpay = 1;
		}
		if($order_info['level_id'] == 4){
			$show_newpay = 2;
		}
		if($order_info['level_id'] == 5){
			$show_newpay = 3;
		}
		  
        $data = array(
            'level_id'=>$order_info['level_id'],
            'expri_day'=>date("Y-m-d",strtotime("$days day")),
			'show_newpay'=>$show_newpay
        );
        //更新数据库
        M('user')->data($data)->where('id='.$order_info['uid'])->save();
        // 加入会员动态（开通会员等级）
        $user = M('user')->where('id='.$order_info['uid'])->find();
        M('user_dynamic')->data(array('mobile'=>$user['username'],'content'=>'成功开通'.$level_info['title'],'t'=>time()))->add();
        // 加入消息通知
        M('user_message')->data(array('uid'=>$user['id'],'content'=>'成功开通会员等级'.$level_info['title'],'t'=>time(),'type'=>2))->add();
        //更新上级邀请人会员团队等级信息
        $this->updateParentUserTeamInfo($user['pid']);
    }
    
    /**
     * 更新上级会员团队等级信息
     * @param number $uid
     */
    private function updateParentUserTeamInfo($uid=0)
    {
        if($uid){
            //已成功推广会员数量
            $countSql = "select count(*) as total_num from dz_user a where a.pid='{$uid}' and a.id in (select b.uid from dz_user_level_buy b where b.`status`=2 group by b.uid)";
            $countQuery = M()->query($countSql);
            $tg_num = $countQuery[0]['total_num'];
            $user = M('user')->where('id='.$uid)->find();
            if($user['team_level']){
                $team_level = M('team_level')->where(array('name'=>$user['team_level']))->find();
                $team_next_level = M('team_level')->where(array('o'=>array('gt',$team_level['o'])))->limit(1)->order('o asc')->select();
                if(!empty($team_next_level)){
                    //判断是否满足升级条件
                    $min_num = $team_next_level[0]['min_num'];
                    if(intval($tg_num) >= intval($min_num) && intval($team_next_level[0]['user_level_id']) > intval($user['level_id'])){
                        // 计算该等级有效天数
                        $level_info = M('user_level')->where('id='.$team_next_level[0]['user_level_id'])->field('expri_day,title')->find();
                        $days = intval($level_info['expri_day']);
                        $data = array(
                            'level_id'=>$team_next_level[0]['user_level_id'],
                            'expri_day'=>date("Y-m-d",strtotime("$days day")),
                            'team_level'=>$team_next_level[0]['name']
                        );
                        M('user')->data($data)->where('id='.$uid)->save();
                        //加入消息通知
                        M('user_message')->data(array('uid'=>$uid,'content'=>'团队等级升级为'.$team_next_level[0]['name'],'t'=>time(),'type'=>2))->add();
                    }
                } 
            }else{
                $team_next_level = M('team_level')->where(array('o'=>1))->find();
                $min_num = $team_next_level['min_num'];
                if(intval($tg_num) >= intval($min_num) && intval($team_next_level['user_level_id']) > intval($user['level_id'])){
                    // 计算该等级有效天数
                    $level_info = M('user_level')->where('id='.$team_next_level['user_level_id'])->field('expri_day,title')->find();
                    $days = intval($level_info['expri_day']);
                    $data = array(
                        'level_id'=>$team_next_level['user_level_id'],
                        'expri_day'=>date("Y-m-d",strtotime("$days day")),
                        'team_level'=>$team_next_level['name']
                    );
                    M('user')->data($data)->where('id='.$uid)->save();
                    //加入消息通知
                    M('user_message')->data(array('uid'=>$uid,'content'=>'团队等级升级为'.$team_next_level['name'],'t'=>time(),'type'=>2))->add();
                }
            }
        }
    }
    
    
    
    
//     public function check()
//     {
//         $uid = I('uid');
//         if($uid){
//             //已成功推广会员数量
//             $countSql = "select count(*) as total_num from dz_user a where a.pid='{$uid}' and a.id in (select b.uid from dz_user_level_buy b where b.`status`=2 group by b.uid)";
//             $countQuery = M()->query($countSql);
//             $tg_num = $countQuery[0]['total_num'];
//             $user = M('user')->where('id='.$uid)->find();
//             if($user['team_level']){
//                 $team_level = M('team_level')->where(array('name'=>$user['team_level']))->find();
//                 $team_next_level = M('team_level')->where(array('o'=>array('gt',$team_level['o'])))->limit(1)->order('o asc')->select();
//                 if(!empty($team_next_level)){
//                     //判断是否满足升级条件
//                     $min_num = $team_next_level[0]['min_num'];
//                     if(intval($tg_num) >= intval($min_num) && intval($team_next_level[0]['user_level_id']) > intval($user['level_id'])){
//                         // 计算该等级有效天数
//                         $level_info = M('user_level')->where('id='.$team_next_level[0]['user_level_id'])->field('expri_day,title')->find();
//                         $days = intval($level_info['expri_day']);
//                         $data = array(
//                             'level_id'=>$team_next_level[0]['user_level_id'],
//                             'expri_day'=>date("Y-m-d",strtotime("$days day")),
//                             'team_level'=>$team_next_level[0]['name']
//                         );
//                         M('user')->data($data)->where('id='.$uid)->save();
//                     }
//                 }
//             }else{
//                 $team_next_level = M('team_level')->where(array('o'=>1))->find();
//                 $min_num = $team_next_level['min_num'];
//                 if(intval($tg_num) >= intval($min_num) && intval($team_next_level['user_level_id']) > intval($user['level_id'])){
//                     // 计算该等级有效天数
//                     $level_info = M('user_level')->where('id='.$team_next_level['user_level_id'])->field('expri_day,title')->find();
//                     $days = intval($level_info['expri_day']);
//                     $data = array(
//                         'level_id'=>$team_next_level['user_level_id'],
//                         'expri_day'=>date("Y-m-d",strtotime("$days day")),
//                         'team_level'=>$team_next_level['name']
//                     );
//                     M('user')->data($data)->where('id='.$uid)->save();
//                 }
//             }
//         }
//     }
}